# !/usr/bin/env python
# -*- coding: utf-8 -*-
# @File  : 单一聚合max、min操作.py
# @Author: dongguangwen
# @Date  : 2025-06-14 19:10
from pymongo import MongoClient

# 连接到MongoDB（默认端口27017）
client = MongoClient('mongodb://root:root123@192.168.1.119:27017/')

# 创建数据库和集合
db = client['learning_mongodb']
collection = db['users']


pipeline_min = [
    {"$group": {"_id": None, "min_age": {"$min": "$age"}}}
]
result = list(db.users.aggregate(pipeline_min))
print(result)
print("最小年龄:", result[0]["min_age"])

pipeline_max = [
    {"$group": {"_id": None, "max_age": {"$max": "$age"}}}
]
result = list(db.users.aggregate(pipeline_max))
print(result)
print("最大年龄:", result[0]["max_age"])

"""
[{'_id': None, 'min_age': 19}]
最小年龄: 19
[{'_id': None, 'max_age': 56}]
最大年龄: 56
"""